package com.team7.happycommunity.propertymanagement.service.impl;

import com.team7.happycommunity.propertymanagement.dao.PropertyManageMapper;
import com.team7.happycommunity.propertymanagement.pojo.PropertyManage;
import com.team7.happycommunity.propertymanagement.service.PropertyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class PropertyServiceImpl implements PropertyService {

    @Autowired
    PropertyManageMapper propertyManageMapper;


    /**
     * 登录业务 包含签名部分，防止信息被篡改
     * @param propertyManage
     * @return
     */
    @Override
    public Boolean login(PropertyManage propertyManage) {
        PropertyManage propertyManage_re = propertyManageMapper.selectByUserName(propertyManage.getUsername());
        // 生成加密后字段

        String result_pass = DigestUtils.md5DigestAsHex((propertyManage.getPassword()+propertyManage_re.getSaltValue()).getBytes());
        if( propertyManage_re.getStatus()== 1 && result_pass.equals(propertyManage_re.getPassword())){
            // 认证成功 返回成功

            return true;
        }else{
            // 认证失败 返回false
            return false;
        }
//        return null;
    }

    @Override
    public PropertyManage selectOneByUsername(String username) {
        return propertyManageMapper.selectByUserName(username);
    }

    @Override
    public Boolean sign(PropertyManage propertyManage) {
        PropertyManage propertyManage_re = propertyManageMapper.selectByUserName(propertyManage.getUsername());
        if(propertyManage_re != null){
            return false;
        }
        String salt = UUID.randomUUID().toString().replace("-","");
        propertyManage.setSaltValue(salt);
        propertyManage.setPassword( DigestUtils.md5DigestAsHex(("111111"+salt).getBytes()));
        propertyManage.setStatus(0);
        propertyManage.setCreateTime(new Date());
        int i = propertyManageMapper.insertSelective(propertyManage);
        return (i == 0)?false:true;
    }

    @Override
    public boolean updatePassWord(String oldpass, String password, String username) {

        PropertyManage propertyManage = propertyManageMapper.selectByUserName(username);
        if(propertyManage == null ){
            return false;
        }
        if(DigestUtils.md5DigestAsHex((oldpass+propertyManage.getSaltValue()).getBytes()).equals(propertyManage.getPassword())){
            // 验证通过
            String newpass = DigestUtils.md5DigestAsHex((password + propertyManage.getSaltValue()).getBytes());
            int i = propertyManageMapper.updatePWDByUsername(newpass, username);
            return (i == 0)?false:true;
        }else{
            return false;
        }
    }
}
